/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
/* eslint-disable react/no-array-index-key */
/* eslint-disable react/jsx-no-undef */
/* eslint-disable no-empty-pattern */
/**
 * 表格组件
 * 组件描述：根据入参生成表格，包括表格头部和表格主体，可以配置表格显示属性和表格列显示属性。
 * @author LiAnqi
 * @Date 2022.2.21
 * @Date 2022.6.8
 */

/* eslint-disable no-debugger */
/* eslint-disable jsx-a11y/anchor-is-valid */
/* eslint-disable react/no-unstable-nested-components */
import React, { useState, useEffect, useRef, useImperativeHandle } from 'react'
import { Space, Row, Col, Menu } from 'antd'
import { SettingOutlined } from '@ant-design/icons'
// import { useMainContext } from '../index'
import FCRichLabel from '../fc-button/FCRichLabel'
import ConfigPanelForTable from './components/ConfigPanelForTable'
import ConfigPanelForColumns from './components/ConfigPanelForColumns'
import TableMain from './components/TableMain'
import ActionCell from './components/ActionCell'
import './FCTable.less'

function FCTable(props) {
  // Props
  const {
    tableRef,
    columns,
    rowKey,
    dataSource,
    pagination,
    rowSelectionType = 'none',
    extraTopRight,
    actionColumn,
    isHeader = false,
    isConfig = false,
    onTableChange = () => {},
    onRowClick = () => {},
    onRowDoubleClick = () => {},
    onSelectionChange = () => {},
    onSelectionSelectChange = () => {},
    onSelectionSelectAllChange = () => {},
    selectedRowKeys,
    showAllRows,
    loading
  } = props
  const { bordered, size, scroll = { y: 0 } } = props
  const { deductHeight=0 } = props // 允许组件外部手动扣除一定高度
  // const { bordered, size, scroll = { y: 500 } } = props
  // debugger

  // table event
  const rowEvents = {
    onRowClick,
    onRowDoubleClick,
  }

  const rowSelection =
    rowSelectionType === 'none'
      ? false
      : {
          selectedRowKeys,
          type: rowSelectionType,
          onChange: onSelectionChange,
          onSelect: onSelectionSelectChange,
          onSelectAll: onSelectionSelectAllChange,
        }

  // configurable table Props
  const [configurableProps, setConfigurableProps] = useState({
    bordered,
    size,
    // scroll,
  })

  // State
  const [mergedColumns, setMergedColumns] = useState([...columns])
  const [ifConfigTable, setIfConfigTable] = useState(false)
  const [ifConfigColumns, setIfConfigColumns] = useState(false)

  // Hook
  // const { onRequestTab } = useMainContext()

  useImperativeHandle(tableRef, () => {
    return {
      setMergedColumns: (e) => setMergedColumns(e),
    }
  })

  // Method
  const showDrawerStyle = () => {
    setIfConfigTable(true)
  }

  const showConfigForColumns = () => {
    setIfConfigColumns(true)
  }

  // Event
  const onCloseDrawerColumns = () => {
    setIfConfigColumns(false)
  }

  const closeDrawerStyle = () => {
    setIfConfigTable(false)
  }

  const handleConfigColumns = ({ index, propName, checked }) => {
    const columnsCopy = [...mergedColumns]
    columnsCopy[index][propName] = checked
    setMergedColumns(columnsCopy)
  }

  const handleColumnsVisible = (e, columnIndex) => {
    const columnsCopy = [...mergedColumns]
    columnsCopy[columnIndex].open = e.target.checked
    setMergedColumns(columnsCopy)
  }

  const handleColumnsFixed = (e, columnIndex) => {
    const columnsCopy = [...mergedColumns]
    columnsCopy[columnIndex].fixed = e.target.checked
    setMergedColumns(columnsCopy)
  }

  const handleTableProps = (prop, value) => {
    const newProps = { ...configurableProps }
    // debugger
    newProps[prop] = value
    setConfigurableProps(newProps)
  }

  // Basic method
  const toDetail = ({ text, link, record }) => {
    const tabPane = {
      type: 'DetailPage',
      title: link.title, // `${detailPage.title}-${text}`,
      key: `detail${new Date().getTime()}`,
      roote: link.roote,
      params: record,
    }
    // onRequestTab(tabPane)
  }

  // Render
  const menuItems = [
    {
      key: '1',
      titil: '配置列',
      label: '配置列 ',
      onClick: (e) => {
        showConfigForColumns()
      },
    },
    {
      key: '2',
      titil: '设置显示风格',
      label: '设置显示风格 ',
      onClick: () => {
        showDrawerStyle()
      },
    },
  ]
  const popoverContent = (
    <Menu style={{ width: 200 }} mode="vertical" theme="light" items={menuItems} />
  )

  const colWithLink = (col) => {
    const { link } = col
    const mCol = {
      ...col,
      render: (text, record, rowIndex) => (
        <a
          href="#"
          onClick={() => {
            toDetail({ text, link, record })
          }}
        >
          {text}
        </a>
      ),
    }
    return mCol
  }

  const parseColumns = () => {
    const cols = []
    mergedColumns?.map((col) => {
      if (col.open) {
        const rCol = col.link ? colWithLink(col) : col
        cols.push(rCol)
      }
    })
    if (actionColumn) {
      const { title: actionTitlle, fixed, elements, ...rest } = actionColumn
      cols.push({
        title: actionTitlle,
        fixed,
        key: 'actionCell9999',
        ...rest, //允许添加额外config列属性
        render: (_, record, index) => (
          <ActionCell elements={elements} record={record} index={index} />
        ),
      })
    }
    return cols
  }

  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  })

  const [windowSize, setWindowSize] = useState(getWindowSize())

  const handleResize = () => {
    // console.log(getWindowSize())
    setWindowSize(getWindowSize())
  }

  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize)

    // 销毁
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  const [scrollY, setScrollY] = useState()
  const [clientTop, setClientTop] = useState(0)
  // 根据页面高度动态设置表格垂直出现滚动的高度
  const tableWrapperRef = useRef(null)
  const setScrollYFun = () => {
    // console.log(tableWrapperRef.current.getBoundingClientRect())
    // console.log(tableWrapperRef.current.getBoundingClientRect().top)
    if (tableWrapperRef.current.getBoundingClientRect().top) {
      const winClientTop = tableWrapperRef.current.getBoundingClientRect().top
      setClientTop(winClientTop)
      setScrollY((preScrollY) => {
        // console.log('showAllRows',showAllRows)
        if (showAllRows) {
          return 'max-content'
        }
        // 表格高度 = 页面高度 - 表格元素距离顶部距离 - 固定值 - 扣除高度
        // console.log(windowSize.innerHeight,winClientTop,)
        return windowSize.innerHeight - winClientTop - 135 - deductHeight
        // return windowSize.innerHeight - winClientTop - (windowSize.innerWidth < 1600 ? 119 : 135) - deductHeight
      })
    } else {
      setScrollY((preScrollY) => {
        if (showAllRows) {
          return 'max-content'
        }
        // 表格高度 = 页面高度 - 表格元素距离顶部距离 - 固定值 - 扣除高度
        return windowSize.innerHeight - clientTop - 135 - deductHeight
        // return windowSize.innerHeight - clientTop - (windowSize.innerWidth < 1600 ? 119 : 135) - deductHeight
      })
    }
  }

  useEffect(()=>{
    setMergedColumns([...columns])
    
    // 页面元素还没有创建完成，使用延迟加载
    if (tableWrapperRef.current.getBoundingClientRect().top) {
      setScrollYFun()
    } else {
      setTimeout(() => {
        setScrollYFun()
      }, 30)
    }

  },[columns])
  
  // useEffect(() => {
  //   // 页面元素还没有创建完成，使用延迟加载
  //   if (tableWrapperRef.current.getBoundingClientRect().top) {
  //     setScrollYFun()
  //   } else {
  //     setTimeout(() => {
  //       setScrollYFun()
  //     }, 30)
  //   }
  // }, [windowSize])

  return (
    <div className="fc-table-container">
      {isHeader ? (<Row
        justify="space-around"
        className="table-header"
      >
        <Col span={6} className="table-header-title">{'title'}</Col>
        <Col span={18} style={{ textAlign: 'right', padding: '0 15px' }}>
          <Space direction="horizontal" align="end">
            {extraTopRight}
            {isConfig ? (
              <FCRichLabel
                size="48"
                text="配置"
                contentTitle=""
                icon={SettingOutlined}
                content={popoverContent}
                placement="bottomLeft"
              />
            ) : null}
          </Space>
          <ConfigPanelForColumns
            ifVisible={ifConfigColumns}
            dataSource={mergedColumns}
            onClose={onCloseDrawerColumns}
            onChange={handleConfigColumns}
          />
          <ConfigPanelForTable
            ifVisible={ifConfigTable}
            onClose={closeDrawerStyle}
            tableProps={configurableProps}
            onChange={handleTableProps}
          />
        </Col>
      </Row>) : null}
      <div className="fc-table-main-container" ref={tableWrapperRef}>
        <TableMain
          loading={loading}
          {...configurableProps}
          columns={parseColumns(mergedColumns)}
          rowKey={rowKey}
          dataSource={dataSource}
          pagination={pagination}
          rowSelection={rowSelection}
          onTableChange={onTableChange}
          scroll={{ ...scroll, y: scroll.y || scrollY }}
          {...rowEvents}
          // size={windowSize.innerWidth < 1600 ? 'small' : 'default'}
        />
        {/*  当分辨率小于1600，将表格size=small */}
      </div>
    </div>
  )
}
export default FCTable
